
from configure.db_configure import db
from common import db_utils
from datetime import datetime
import action.ws as ws

CREATE_SQL ='''
    CREATE TABLE IF NOT EXISTS t_info
    (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    type    VARCHAR(32)    NOT NULL,
    content    VARCHAR(4096)    NOT NULL,
    createTime     DATETIME     NOT NULL,
    updateTime     DATETIME     NOT NULL
    );
    '''

CREATE_SQL_HISTORY ='''
    CREATE TABLE IF NOT EXISTS t_info_history
    (
    id INT PRIMARY KEY ,
    type    VARCHAR(32)    NOT NULL,
    content    VARCHAR(4096)    NOT NULL,
    createTime     DATETIME     NOT NULL,
    updateTime     DATETIME     NOT NULL
    );
    '''

def save(type,content):
    now = datetime.now()
    entity = {
        "type":type,
        "content": content.replace("，",","),
        "createTime":now,
        "updateTime":now
      }
    with db() as session:
        session.insertEntity("t_info",entity)
        ws.emit("info")
        return entity


def saves(type:str,contents:str):
    now = datetime.now()
    entityList = []
    contentList = contents.splitlines()

    for content in contentList:
        if len(content.strip()) > 0 :
            entity = {}
            entity["type"] = type
            entity["content"] = content.replace("，",",")
            entity["createTime"] = now
            entity["updateTime"] = now
            entityList.append(entity)

    if len(contentList) > 0:
        with db() as session:
            session.insertEntityBatch("t_info",entityList)
        ws.emit("info")


def findPage(type:str,pageNum:int,pageSize:int):
    offsize = db_utils.limitStart(pageNum,pageSize)
    with db() as session:
        total = session.findOne("select count(*) as num from t_info where type=? ", (type,))
        items = session.findList2("select * from t_info where type=? order by id desc limit ?,?",(type,offsize,pageSize) )
        return {
            "total":total,
            "items":items
        }
        

def findPageHistory(type:str,pageNum:int,pageSize:int):
    offsize = db_utils.limitStart(pageNum,pageSize)
    with db() as session:
        total = session.findOne("select count(*) as num from t_info_history where type=? ", (type,))
        items = session.findList2("select * from t_info_history where type=? order by id desc limit ?,?",(type,offsize,pageSize) )
        return {
            "total":total,
            "items":items
        }
        

def pop(type) ->tuple:
    ''' 消费若干种资料'''
    with db() as session:
        entity = session.findOne2("select * from t_info where type = ? order by id limit 1",(type,))
        if entity != None :
            session.deleteById("t_info",entity["id"])
            session.insertEntity("t_info_history",entity)

            content:str = entity["content"]
            contentArr = content.split(",")
            ws.emit("info")
            return tuple(contentArr)
        else:
            return None
    
    #删除info 写入 info_history

def pops(typeList) ->list:
    ''' 消费若干种资料'''
    try:
        with db() as session:
            infoContentList = []
            for type in typeList:
                infoContent = pop(type)
                if infoContent == None:
                    raise Exception("资料不足")
                infoContentList.append(infoContent)
            ws.emit("info")
            return infoContentList
    except:
        return []